<script setup>
import {onMounted} from 'vue'
import {
  NAvatar,
  NButton,
  NFlex,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSelect,
  NTabPane,
  NTabs,
  NTag,
  useMessage
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import api from '@/api'
import default_image from "@/assets/images/mz.jpg";
import {getToken, renderIcon} from "@/utils";
import TheIcon from "@/components/icon/TheIcon.vue";
import {useCRUD} from "@/composables";
const base_path = import.meta.env.VITE_BASE
const message = useMessage()
const {
  modalVisible,
  modalAction,
  modalTitle,
  modalLoading,
  handleAdd,
  handleDelete,
  handleEdit,
  handleSave,
  modalForm,
  modalFormRef,
} = useCRUD({
  name: '划扣',
  initForm: {},
  doCreate: api.createCases,
  doDelete: api.deleteCases,
  doUpdate: api.updateCases,
  refresh: () => on_ref(),
})

const props = defineProps({
  infoData: {
    type: Object,
    required: true
  }
});
const data = reactive({
    projects:[],
    card_loading:false,
    loading:false,
    keyword:"",
    select_projects:[],
    meeting_users:[],
    config:[],
    department:[],
    uploadAction: base_path+'/system/base/userimg',
    token: getToken(),
    giveForm: {
     user_id:'',
     projectstat_ids:[],
     remark:''
    },
    show_give:false,
    customers:[],
    search_loading:false,
    show_give_list:false,
    give_list:[],
    give_type:1,
    give_loading:false,
});

onMounted(() => {
  data.select_customer = props.infoData
  on_ref()
})

function on_ref(){
  data.select_projects = []
  data.keyword = ""
  get_project_list()

}

function get_project_list(){
  data.card_loading = true
  api.getProjectStat({
    user_id:data.select_customer.user_id,
    keyword:data.keyword
  }).then((res) => {
     data.projects = res.data.projects
     data.card_loading = false
     data.loading = false
  })
}

function search_project() {
  data.loading = true;
  const keywords = data.keyword.toLowerCase().trim().split(/\s+/); // 支持空格分隔多关键词

  data.projects = data.projects.map(project => {
    const projectName = project.project_name.toLowerCase();
    // 如果无搜索词或匹配任意关键词
    const shouldShow = keywords.length === 0 || keywords.some(kw => projectName.includes(kw));
    return {
      ...project,
      show: shouldShow ? 1 : 0
    };
  });
  data.loading = false;
}

function update_select(){
  //更新选中的项目
  data.select_projects = []
  data.projects.map(project => {
     if(project.num>0){
       data.select_projects.push(project)
     }
  });
}

function remove_project(item){
  data.projects.map(project => {
     if(project.id===item.id){
       project.num = 0
     }
  });
  update_select()
}

function add_cases(){
  if(data.select_projects.length<=0){
    message.error("请先选择划扣项目")
    return
  }
  api.getConfig().then((res) => {
     data.config = res.data
  })

  api.getDepartment().then((res) => {
     data.department = res.data
  })

  api.getMeetingUsers({types:4}).then((res) => {
     data.meeting_users = res.data.list
  })
  handleAdd()
  modalForm.value.address_id = 1
  modalForm.value.project_id = data.select_projects
  modalForm.value.user_id = data.select_customer.user_id
}

function create_cases(){
  // 驗證必填欄位
  if (!modalForm.value.doctor) {
    message.error("请选择医生")
    return
  }
  if (!modalForm.value.face_id) {
    message.error("请选择护士")
    return
  }

  modalForm.value.project_id = JSON.stringify(modalForm.value.project_id);
  if(modalForm.value.voucher_images){
    modalForm.value.voucher_images = modalForm.value.voucher_images.map(item => item.url);
  }
  if(modalForm.value.after_images){
    modalForm.value.after_images = modalForm.value.after_images.map(item => item.url);
  }
  if(modalForm.value.before_images){
    modalForm.value.before_images = modalForm.value.before_images.map(item => item.url);
  }



  handleSave()
}

const handleFinish = ({ file, event }) => {
  let data = (event?.target).response
  data = JSON.parse(data)
  if (data.code === 200) {
    file.url = data.data.url
    message.success('上传成功')
  } else {
    message.error(data.data)
  }
  return file
}

function add_give(){
  if(data.select_projects.length<=0){
    message.error("请先选择赠送项目")
    return
  }
  data.show_give = true
  data.giveForm.projectstat_ids = data.select_projects
}

function create_give(){
  if(!data.giveForm.user_id){
    message.error("请先选择受赠人")
    return
  }
  data.giveForm.projectstat_ids = JSON.stringify(data.giveForm.projectstat_ids);
  api.createGive(data.giveForm).then((res) => {
     message.success('赠送完成,等待财务审核')
     data.show_give = false
     on_ref()
  })
}

function search_customer(query){
  data.search_loading = true
  api.getCustomers({keyword:query}).then((res) => {
     data.customers = res.data.items
     data.search_loading = false
  })
}

function list_give(){
  data.show_give_list = true
  data.give_loading = true
  api.getProjectGiveList({
    user_id:data.select_customer.user_id,
    type:data.give_type
  }).then((res) => {
     data.give_list = res.data
    data.give_loading = false
  })

}

</script>

<template>
  <div class="container" style="height: calc(100vh - 106px);">
    <div class="search">
      <NInput size="large" @change="search_project" v-model:value="data.keyword"  :loading="data.loading" clearable type="text" placeholder="请输入卡项,项目名称检索"/>
    </div>
     <n-spin :show="data.card_loading" style="--n-opacity-spinning:0.1;height: calc(100vh - 405px);">
       <n-scrollbar v-if="data.projects.length>0" style="max-height: calc(100vh - 405px);padding:0 20px 20px 0px">
        <n-grid x-gap="12" y-gap="12" :cols="3">
        <n-gi v-for="item in data.projects" v-show="item.show===1">
            <n-card  embedded hoverable content-style="padding: 0px;" :segmented="{content: true,footer: 'soft',}">
              <template #header>
                <div style="display: flex; align-items: center;justify-content: flex-start">
                  <n-h6 prefix="bar" type="info" style="margin: 0;font-size: 16px">
                    <div style="display: flex">
                    <div style="height:40px;line-height:20px;margin-left: 0px">
                        {{item.project_name}}<span style="font-size: 12px"></span>
                      <br>
                      <span style="font-size: 12px;color:#747586">单号:{{item.order_id}}</span>&nbsp;<span style="font-size: 12px;color:#747586">购于:{{item.time}}</span>
                    </div>
                    </div>
                  </n-h6>
                </div>
              </template>
              <template #header-extra>
                <n-button type="primary" dashed >剩{{item.number}}/共{{item.all_number}}</n-button>
              </template>

              <div class="huakou_list">
                <n-input-number v-if="item.number>0" v-model:value="item.num" style="width: 100%" :min="0" :max="item.number"  placeholder="本次划扣" @update:value="update_select"/>
              </div>
            </n-card>
        </n-gi>
        </n-grid>

      </n-scrollbar>
       <n-empty v-else description="暂无数据"  style="margin: 50px"></n-empty>
     </n-spin>

    <div class="add_cases">
       <NFlex style="align-items: flex-start;height: 100%;" justify="space-between">

         <div class="selected-projects">
           <div v-if="data.select_projects.length>0" style="margin-right: 10px;margin-top: 10px">已选项目:</div>
           <n-badge :value="'x'+item.num" :max="15" :show="1" style="margin-right: 15px;margin-top: 10px" v-for="item in data.select_projects">
                <n-popconfirm @positive-click="remove_project(item)">
                <template #trigger>
                   <n-tag :bordered="false" type="success" size="large">
                  {{item.project_name}}
                </n-tag>
                </template>
                确定要移除此项目吗？
              </n-popconfirm>
           </n-badge>
         </div>

         <div class="actions-fixed">
          <n-button type="primary" style="margin-right: 10px"  @click="add_cases">
            <TheIcon icon="material-symbols:add" :size="16" class="mr-5" />
              执行划扣
          </n-button>
          <n-button type="primary" style="margin-right: 10px" @click="add_give">
            <TheIcon icon="material-symbols:next-plan-outline-rounded" :size="16" class="mr-5" />
              执行转赠
          </n-button>
          <n-button type="primary" style="margin-right: 30px" @click="list_give">
            <TheIcon icon="material-symbols:event-list-outline-sharp" :size="16" class="mr-5" />
              转赠记录
          </n-button>
         </div>
       </NFlex>
    </div>

  </div>


  <n-drawer v-model:show="modalVisible" width="760px">
      <n-drawer-content title="划扣" closable>
        <NForm
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="80"
        :model="modalForm"
      >
          <NFormItem label="选择门店" path="address_id">
          <NSelect
              v-model:value="modalForm.address_id"
              :options="data.config.address"
              placeholder="选择门店"
              filterable
              label-field="name"
              value-field="id"
              style="width: 593px"
            />
        </NFormItem>
        <NFormItem label="选择医生" path="doctor">
          <NSelect
              v-model:value="modalForm.doctor"
              :options="data.config.doctor"
              placeholder="选择医生"
              filterable
              label-field="name"
              value-field="id"
              style="width: 593px"
            />
        </NFormItem>
          <NFormItem label="选择护士" path="face_id">
          <NSelect
              v-model:value="modalForm.face_id"
              :options="data.meeting_users"
              placeholder="选择护士"
              filterable
              label-field="name"
              value-field="id"
              style="width: 593px"
            />
        </NFormItem>
<!--          <NFormItem label="选择科室" path="department">-->
<!--          <NSelect-->
<!--              v-model:value="modalForm.department"-->
<!--              :options="data.config.deps"-->
<!--              placeholder="选择科室"-->
<!--              filterable-->
<!--              label-field="name"-->
<!--              value-field="id"-->
<!--              style="width: 593px"-->
<!--            />-->
<!--        </NFormItem>-->

          <NFormItem label="划扣项目" path="project_id">
          <n-layout>
                <n-layout-header>
                  <n-flex >
                    <n-tag size="large" style="width:100px"> 项目编号 </n-tag>
                    <n-tag size="large" style="width: 250px"> 项目名称 </n-tag>
                    <n-tag size="large" style="width: 100px"> 划扣数量 </n-tag>
                  </n-flex>
                </n-layout-header>
                <n-layout-content content-style="padding: 10px 0;">
                  <n-dynamic-input v-model:value="modalForm.project_id" disabled>
                    <template #default="{ value }">
                      <n-flex justify="space-between">
                        <n-input  v-model:value="value.id" style="width: 100px" disabled/>
                        <n-input  v-model:value="value.title" style="width: 250px" disabled/>
                        <n-input  v-model:value="value.num" style="width: 100px" disabled/>
                      </n-flex>
                    </template>
                  </n-dynamic-input>
                </n-layout-content>
              </n-layout>
        </NFormItem>

        <NFormItem label="备注" path="remark">
          <NInput type="textarea" v-model:value="modalForm.remark" placeholder="请输入备注" style="width: 593px"/>
        </NFormItem>

<!--          <NFormItem label="回访计划" path="plan_type">-->
<!--          <NSelect-->
<!--              v-model:value="modalForm.plan_type"-->
<!--              :options="data.config.plan_type"-->
<!--              placeholder="选择回访计划"-->
<!--              filterable-->
<!--              label-field="name"-->
<!--              value-field="id"-->
<!--              style="width: 593px"-->
<!--            />-->
<!--        </NFormItem>-->
<!--          <NFormItem label="开始日期" path="visit_date">-->
<!--          <n-date-picker-->
<!--            v-model:formatted-value="modalForm.visit_date"-->
<!--            value-format="yyyy-MM-dd"-->
<!--            type="date"-->
<!--            clearable-->
<!--            placeholder="请输入回访计划开始执行日期"-->
<!--            style="width: 593px"-->
<!--          />-->
<!--        </NFormItem>-->



              <n-tabs type="line" animated>
                <n-tab-pane name="voucher_images" tab="术前协议">
                    <NFormItem label="" path="voucher_images" style="width: 100%">
                          <NUpload :action="data.uploadAction" :headers="{ authorization: data.token }" multiple list-type="image-card"
                                   @finish="handleFinish" v-model:file-list="modalForm.voucher_images">
                          </NUpload>
                    </NFormItem>
                </n-tab-pane>
                <n-tab-pane name="before_images" tab="术前照">
                  <NFormItem label="" path="before_images" style="width: 100%">
                          <NUpload :action="data.uploadAction" :headers="{ authorization: data.token }" multiple list-type="image-card"
                                   @finish="handleFinish" v-model:file-list="modalForm.before_images">
                          </NUpload>
                    </NFormItem>
                </n-tab-pane>
                <n-tab-pane name="after_images" tab="术后照">
                  <NFormItem label="" path="after_images" style="width: 100%">
                          <NUpload :action="data.uploadAction" :headers="{ authorization: data.token }" multiple list-type="image-card"
                                   @finish="handleFinish" v-model:file-list="modalForm.after_images">
                          </NUpload>
                    </NFormItem>
                </n-tab-pane>
              </n-tabs>


      </NForm>
         <template #footer>
        <n-button type="primary"   @click="create_cases">
          <TheIcon icon="material-symbols:database-upload-outline" :size="16" class="mr-5" />保存</n-button>
      </template>

      </n-drawer-content>


    </n-drawer>
  <n-drawer v-model:show="data.show_give" width="760px">
      <n-drawer-content title="转赠" closable>
        <NForm
        ref="modalFormRef"
        label-placement="left"
        label-align="left"
        :label-width="100"
        :model="data.giveForm"
      >

        <NFormItem label="选择受赠人" path="user_id">
          <NSelect
              v-model:value="data.giveForm.user_id"
              :options="data.customers"
              placeholder="选择受赠人"
              filterable
              label-field="all_name"
              value-field="user_id"
              style="width: 593px"
              :loading="data.search_loading"
              remote
              clearable
              @search="search_customer"
            />
        </NFormItem>


          <NFormItem label="赠送项目" path="projectstat_ids">
          <n-layout>
                <n-layout-header>
                  <n-flex >
                    <n-tag size="large" style="width:100px"> 项目编号 </n-tag>
                    <n-tag size="large" style="width: 250px"> 项目名称 </n-tag>
                    <n-tag size="large" style="width: 100px"> 划扣数量 </n-tag>
                  </n-flex>
                </n-layout-header>
                <n-layout-content content-style="padding: 10px 0;">
                  <n-dynamic-input v-model:value="data.giveForm.projectstat_ids" disabled>
                    <template #default="{ value }">
                      <n-flex justify="space-between">
                        <n-input  v-model:value="value.id" style="width: 100px" disabled/>
                        <n-input  v-model:value="value.title" style="width: 250px" disabled/>
                        <n-input  v-model:value="value.num" style="width: 100px" disabled/>
                      </n-flex>
                    </template>
                  </n-dynamic-input>
                </n-layout-content>
              </n-layout>
        </NFormItem>

        <NFormItem label="赠送备注" path="remark">
          <NInput type="textarea" v-model:value="data.giveForm.remark" placeholder="请输入赠送备注" style="width: 593px"/>
        </NFormItem>


      </NForm>
         <template #footer>
        <n-button type="primary" @click="create_give">
          <TheIcon icon="material-symbols:database-upload-outline" :size="16" class="mr-5" />保存</n-button>
      </template>

      </n-drawer-content>


    </n-drawer>
  <n-drawer v-model:show="data.show_give_list" width="600px">
      <n-drawer-content title="转赠记录" closable>
        <n-spin :show="data.give_loading" style="--n-opacity-spinning:0.1;height: 100%">
        <n-card style="margin-bottom: 20px" v-for="item in data.give_list" size="small" :segmented="{content: true,footer: 'soft',}">
          <template #header>
            <div style="display: flex; align-items: center;justify-content: flex-start">
              <n-h6 prefix="bar" type="info" style="margin: 0;font-size: 16px">
                <div style="display: flex">
                <n-button type="info" dashed size="large">转赠单号:{{item.id}}</n-button>
              <div style="height:40px;line-height:20px;margin-left: 10px">
                <span style="margin-right: 5px">
                  {{item.project_name}}<span style="font-size: 12px">X{{item.nums}}</span>
                </span>
                <br>
                <span style="font-size: 12px;color:#747586">赠送于:{{item.created_at}}</span>
              </div>
                </div>
              </n-h6>
            </div>
          </template>

          <template #header-extra>
            <n-button type="primary" dashed disabled >{{item.states_name}}</n-button>
          </template>

          <div style="display: flex;font-size: 16px;color: #aaa;align-items: center">
            <n-button type="error"   disabled >发起人:{{item.old_user_name}}</n-button>&nbsp;->&nbsp;
            <n-button type="primary"  disabled >受赠人:{{item.new_user_name}}</n-button>
          </div>

        </n-card>
        </n-spin>
      </n-drawer-content>
  </n-drawer>


</template>

<style>
 .container{
   padding: 10px;
   /* transform: translate(0); */
   position: relative;
   height:100%;
   .search{
     margin-bottom: 10px;
   }
 }
 .cards{
   margin:0px;
 }
 .project{margin-bottom: 10px;}
 .huakou_list{
   padding: 20px;
   border-radius: 10px;
 }
 .add_cases{
   height:200px!important;
   position: absolute;
   bottom: 0;
   background: #eee;
   width: 100%;
   padding: 10px;
   border-top-left-radius: 5px;
  overflow: hidden;
 }
 .add_cases .selected-projects{
   display: flex;
   align-items: flex-start;
   flex-wrap: wrap;
   gap: 10px 15px;
   overflow-y: auto;
   overflow-x: hidden;
   padding-right: 360px; /* avoid overlap with fixed actions */
   margin-top: 0;
   height: 100%;
 }
 .add_cases .actions-fixed{
   position: absolute;
   right: 10px;
   bottom: 10px;
   display: flex;
   align-items: center;
 }
</style>